import time
from . import ConnPG
import psycopg2
from sanic.log import logger

class SubjectTable:

    async def add_subject(self, subject_name):#添加公司或项目

        #参数检查

        if not subject_name:

            return {
                'status': -1,
                'errorCode': 302100,
                'errorMsg': '公司或项目名不能为空',
                'resultBody': None
            }

        sql = 'INSERT INTO subject(subject_name) VALUES (%s)'

        try:
            await ConnPG().execute(sql, (subject_name,))
        except psycopg2.errors.UniqueViolation:

            return {
                'status': -1,
                'errorCode': 302101,
                'errorMsg': '当前公司或项目名已经存在',
                'resultBody': None,
            }
        else:
        
            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': "公司或项目添加成功",
            }

    async def select_all_subject(self):#查看所有公司或项目

        sql = 'select * from subject'

        result = await ConnPG().fetchall(sql)

        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': result,
        }

    async def del_subject(self, subject_id):#删除subject

        #参数检查

        if not subject_id or not subject_id.isdecimal:

            return {
                'status': -1,
                'errorCode': 302100,
                'errorMsg': '公司或项目id不能为空且为整数类型',
                'resultBody': None
            }

        sql = 'DELETE FROM subject WHERE id=%s'

        try:
            await ConnPG().execute(sql, (subject_id,))
        except psycopg2.errors.ForeignKeyViolation as e:

            # print(e)

            return {

                'status': -1,
                'errorCode': 302112,
                'errorMsg': str(e),
                'resultBody': None,
            }
        else:
        
            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': "公司或项目删除成功",
            }

    async def update_subject(self, subject_id, subject_name):#更新库房名称

        #参数检查
        if not all([subject_id, subject_name]) or not subject_id.isdecimal():


            return {
                'status': -1,
                'errorCode': 302100,
                'errorMsg': '接口有两个必传参数且subject_id为整数',
                'resultBody': None
            }

        sql = "UPDATE subject SET subject_name=%s WHERE id=%s"


        await ConnPG().execute(sql, (subject_name,subject_id))

    
        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': "名称修改成功",
        }
    